1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
/*!
Terms in `isotope`'s underlying dependent type system
*/
use crate::*;

pub mod dynamic;
pub mod flags;
pub mod weak;

mod annot;
mod app;
mod code;
mod lambda;
mod path;
mod pi;
mod term_impl;
mod universe;
mod var;
mod finite;
mod case;

pub use annot::*;
pub use app::*;
pub use code::*;
pub use lambda::*;
pub use path::*;
pub use pi::*;
pub use term_impl::*;
pub use universe::*;
pub use var::*;
pub use finite::*;
pub use case::*;

/// Objects which can be consed in a context
pub trait Cons {
    /// The type this conses to
    type Consed;

    /// Cons this term within a given context. Return `None` if already consed.
    fn cons(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Option<Self::Consed>;

    /// Get this term, but consed
    fn consed(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Self::Consed {
        if let Some(consed) = self.cons(ctx) {
            consed
        } else {
            self.to_consed_ty()
        }
    }

    /// Convert this term to it's own consed type
    fn to_consed_ty(&self) -> Self::Consed;
}

/// Objects which can be substituted in a context
pub trait Substitute: Cons {
    /// The type this substitutes to
    type Substituted;

    /// Substitute this value recursively
    fn subst_rec(
        &self,
        ctx: &mut (impl SubstCtx + ?Sized),
    ) -> Result<Option<Self::Substituted>, Error>;

    /// Shift this term's variables with index `>= base` in a given context
    fn shift(
        &self,
        shift: i32,
        base: u32,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<Self::Substituted>, Error> {
        self.subst_rec(&mut Shift::new(shift, base, TrivialCons::with_cons(ctx)))
    }

    /// Shift this term's variables with index `>= base` in a given context
    fn shifted(
        &self,
        shift: i32,
        base: u32,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Self::Substituted, Error> {
        if let Some(subst) = self.subst_rec(&mut Shift::new(
            shift,
            base,
            TrivialCons::with_cons(&mut *ctx),
        ))? {
            Ok(subst)
        } else {
            let consed = self.consed(ctx);
            Ok(Self::from_consed(consed, ctx))
        }
    }

    /// Substitute this term's variables with index `>= base` down a variable in a given context
    fn subst_vals<B>(
        &self,
        vals: &[B],
        base: u32,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<Self::Substituted>, Error>
    where
        B: Borrow<TermId>,
    {
        self.subst_rec(&mut SubstSlice::new_with(vals, base, ctx)?)
    }

    /// Convert this object's consed form to it's substituted form
    fn from_consed(this: Self::Consed, ctx: &mut (impl ConsCtx + ?Sized)) -> Self::Substituted;
}

/// Objects which can be type-checked in a context
pub trait Typecheck: HasDependencies + Debug {
    /// *Locally* typecheck a term: note this is context-independent, without caching
    fn do_local_tyck(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> bool;

    /// *Globally* typecheck a term, i.e. typecheck all subterms, without caching
    fn do_global_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool>;

    /// Typecheck this term's annotation, without caching
    fn do_annot_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool>;

    /// *Locally* typecheck a term: note this is context-independent.
    fn local_tyck(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> bool {
        match self.load_flags().get_flag(LocalTyck) {
            L4::True => true,
            L4::False => false,
            L4::Unknown => {
                let result = self.do_local_tyck(ctx);
                self.set_flags(TyckFlags::EMPTY.with_flag(LocalTyck, result.into()));
                result
            }
            L4::Both => panic!("Invalid local type-check flag"),
        }
    }

    /// *Globally* typecheck a term, i.e. typecheck all subterms *and* their variables
    fn global_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        if let Some(approx) = ctx.approx_global_tyck(self.load_flags(), self.get_filter()) {
            Some(approx)
        } else {
            let result = self.do_global_tyck(ctx)?;
            self.set_flags(
                TyckFlags::EMPTY.with_flag(
                    GlobalTyck,
                    ctx.global_tyck_mask(self.get_filter())
                        .intersection(result.into()),
                ),
            );
            Some(result)
        }
    }

    /// *Variable* typecheck a term, i.e. typecheck all subterms *and* their variables.
    fn var_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        if let Some(approx) = ctx.approx_var_tyck(self.load_flags(), self.get_filter()) {
            Some(approx)
        } else {
            let result = self.do_global_tyck(ctx)? && self.do_annot_tyck(ctx)?;
            self.set_flags(
                TyckFlags::EMPTY
                    .with_flag(
                        VarTyck,
                        ctx.var_tyck_mask(self.get_filter())
                            .intersection(result.into()),
                    )
                    .with_flag(
                        AnnotTyck,
                        ctx.annot_tyck_mask(self.get_filter())
                            .intersection(result.into()),
                    )
                    .with_flag(
                        GlobalTyck,
                        ctx.global_tyck_mask(self.get_filter())
                            .intersection(result.into()),
                    ),
            );
            Some(result)
        }
    }

    /// Typecheck this term's annotation
    fn annot_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        if let Some(approx) = ctx.approx_annot_tyck(self.load_flags(), self.get_filter()) {
            Some(approx)
        } else {
            let result = self.do_annot_tyck(ctx)?;
            self.set_flags(
                TyckFlags::EMPTY.with_flag(
                    AnnotTyck,
                    ctx.annot_tyck_mask(self.get_filter())
                        .intersection(result.into()),
                ),
            );
            Some(result)
        }
    }

    /// *Globally* typecheck a term *and* it's annotation, i.e. typecheck all subterms, annotation subterms, *and* their variables
    fn global_var_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        let flags = self.load_flags();
        let filter = self.get_filter();
        match (
            ctx.approx_var_tyck(flags, filter),
            ctx.approx_global_tyck(flags, filter),
        ) {
            (Some(true), Some(true)) => Some(true),
            (Some(false), _) | (_, Some(false)) => Some(false),
            _ => {
                let global_tyck: L4 = self.do_global_tyck(ctx).into();
                let annot_tyck: L4 = self.do_annot_tyck(ctx).into();
                let result = global_tyck.conjunction(annot_tyck);
                self.set_flags(
                    TyckFlags::EMPTY
                        .with_flag(
                            VarTyck,
                            ctx.var_tyck_mask(self.get_filter()).intersection(result),
                        )
                        .with_flag(
                            AnnotTyck,
                            ctx.annot_tyck_mask(self.get_filter())
                                .intersection(annot_tyck),
                        )
                        .with_flag(
                            GlobalTyck,
                            ctx.global_tyck_mask(self.get_filter())
                                .intersection(global_tyck),
                        ),
                );
                result.truth_value()
            }
        }
    }

    /// Typecheck a term in a given context
    fn tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        // If possible, skip type-checking altogether
        if let Some(approx) = ctx.approx_tyck(self.load_flags(), self.get_filter()) {
            return Some(approx);
        }

        // Type-check annotation
        if !self.local_tyck(ctx.cons_ctx()) {
            //TODO: better consing...
            Some(false)
        } else if !self.global_var_tyck(ctx)? {
            Some(false)
        } else {
            Some(true)
        }
    }

    /// Load this term's current flags
    fn load_flags(&self) -> TyckFlags;

    /// Set this term's flags. May cause errors if done incorrectly!
    fn set_flags(&self, flags: TyckFlags);

    /// Typecheck this term along with it's variables
    #[inline]
    fn tyck_var(&self, ctx: &mut (impl TyCtxMut + ConsCtx + ?Sized)) -> Option<bool> {
        self.tyck(&mut MapTyCtx::new(ctx))
    }

    /// Whether this term might be type-checked
    #[inline]
    fn maybe_tyck(&self) -> bool {
        self.load_flags().get_tyck().maybe_true()
    }
}

/// Objects which have value dependencies
pub trait HasDependencies {
    /// Whether this term depends on a variable with a given index: if equiv is true, also consider larger variables in the same equivalence class
    fn has_var_dep(&self, ix: u32, equiv: bool) -> bool;

    /// Get whether a term depends on a variable `base <= variable <= ix`
    ///
    /// Unlike `has_var_dep`, ignores annotations
    fn has_dep_below(&self, ix: u32, base: u32) -> bool;

    /// Get the variable filter of this term
    fn get_filter(&self) -> VarFilter;

    /// Get the free variable bound of this term
    #[inline]
    fn fvb(&self) -> u32 {
        self.get_filter().fvb()
    }
}

/// Objects which may be determined equivalent by terms
pub trait TermEq {
    /// Compare this value to another within a given context
    fn eq_in(&self, other: &Self, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool>;
}

/// A trait implemented by values in `isotope`'s term language
pub trait Value: Debug + Cons + Substitute + Typecheck + HasDependencies + TermEq + Clone {
    /// The type of value this is consed to
    type ValueConsed: From<Self::Consed> + Value;

    /// The type of value this is substituted to
    type ValueSubstituted: From<Self::Substituted> + Value;

    /// Convert this term to a `Term`, without any consing
    fn into_term_direct(self) -> Term;

    /// Get the type annotation of this term
    fn annot(&self) -> Option<AnnotationRef>;

    /// Get the index of this term in a program graph. Return `None` if this term is unindexed
    fn id(&self) -> Option<NodeIx> {
        None
    }

    /// Get whether this term is a type
    fn is_local_ty(&self) -> Option<bool>;

    /// Get whether this term is a universe
    fn is_local_universe(&self) -> Option<bool>;

    /// Get whether this term is a function
    fn is_local_function(&self) -> Option<bool>;

    /// Get whether this term is a dependent function type
    fn is_local_pi(&self) -> Option<bool>;

    /// Get whether this term is in "root form"
    fn is_root(&self) -> bool;

    /// Coerce this term to another type, *with* type-checking
    fn coerce(
        &self,
        ty: Option<TermId>,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<Self::ValueConsed>, Error> {
        if let Some(ty) = ty {
            if let Some(annot) = self.annot() {
                if let Some(annot) = annot.coerce_ty(&ty, ctx)? {
                    self.annotate_unchecked(annot, ctx.cons_ctx())
                } else {
                    Ok(None)
                }
            } else {
                self.annotate_unchecked(Annotation::from_ty(ty)?, ctx.cons_ctx())
            }
        } else {
            Ok(None)
        }
    }

    /// Coerce this term to another type, *with* type-checking
    fn coerce_id(
        &self,
        ty: Option<TermId>,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        if let Some(coerced) = self.coerce(ty, ctx)? {
            Ok(Some(coerced.into_id_with(ctx.cons_ctx())))
        } else {
            Ok(None)
        }
    }

    /// Coerce this term to another type, *with* type-checking
    fn coerced(
        &self,
        ty: Option<TermId>,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Self::ValueConsed, Error> {
        if let Some(coerced) = self.coerce(ty, ctx)? {
            Ok(coerced)
        } else {
            Ok(self.consed(ctx.cons_ctx()).into())
        }
    }

    /// Coerce this term to another type, *with* type-checking
    fn coerced_id(
        &self,
        ty: Option<TermId>,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<TermId, Error> {
        if let Some(coerced) = self.coerce_id(ty, ctx)? {
            Ok(coerced)
        } else {
            Ok(self.clone_into_id_with(ctx.cons_ctx()))
        }
    }

    /// Convert this term to an annotation, with only rudimentary type-checking
    fn annotate_unchecked(
        &self,
        annot: Annotation,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<Self::ValueConsed>, Error>;

    /// Convert this term to an annotation, with only rudimentary type-checking
    fn annotate_unchecked_id(
        &self,
        annot: Annotation,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        if let Some(term) = self.annotate_unchecked(annot, ctx)? {
            Ok(Some(term.into_id_with(ctx)))
        } else {
            Ok(None)
        }
    }

    /// Convert this term to an annotation, with only rudimentary type-checking
    fn annotated_unchecked(
        &self,
        annot: Annotation,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Self::ValueConsed, Error> {
        if let Some(term) = self.annotate_unchecked(annot, ctx)? {
            Ok(term)
        } else {
            Ok(self.consed(ctx).into())
        }
    }

    /// Convert this term to an annotation, with only rudimentary type-checking
    fn annotated_unchecked_id(
        &self,
        annot: Annotation,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<TermId, Error> {
        if let Some(term) = self.annotate_unchecked_id(annot, ctx)? {
            Ok(term)
        } else {
            Ok(self.clone_into_id_with(ctx))
        }
    }

    /// Get whether this term is a constant.
    fn is_const(&self) -> bool {
        self.id().is_none()
    }

    /// Get whether this term is a subtype of another in a given context
    fn is_subtype_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool>;

    /// Get whether this term is a subtype of another in general
    fn is_subtype(&self, other: &Term) -> Option<bool> {
        self.is_subtype_in(other, &mut Untyped)
    }

    /// Cast this *type* into another in a given typing context
    fn coerce_annot_ty(
        &self,
        target: &TermId,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<Annotation>, Error> {
        if let Some(true) = self.is_subtype(target) {
            Ok(None)
        } else {
            Annotation::new(self.into_id_with(ctx.cons_ctx()), target.clone(), ctx).map(Some)
        }
    }

    /// Get whether this term has a universe *in all contexts*
    #[inline]
    fn universe(&self) -> Option<Universe> {
        if let Some(annot) = self.annot() {
            annot.borrow_annot().as_universe()
        } else {
            None
        }
    }

    /// Get whether this term has a pi type *in all contexts*
    #[inline]
    fn fn_ty(&self) -> Option<&Pi> {
        if let Some(annot) = self.annot() {
            annot.as_pi()
        } else {
            None
        }
    }

    /// Get the hash-code of this term
    ///
    /// It is an invariant that, if two terms `t`, `u` differ only due to typing
    /// annotations for any subterm, `t.code().pure() == u.code.pure()`.
    fn code(&self) -> Code;

    /// Get the hash-code of this term if it was untyped
    ///
    /// This can be helpful in, e.g., looking up the untyped term in a hash-map
    /// when one only has the typed term. It is an invariant that, for all terms
    /// `t`, `t.code().pure() == t.untyped_code().pure()`. On the other hand, it
    /// is *not* necessarily the case that `t.ty() == None` implies that
    /// `t.code() == t.untyped_code()`, since while `t` itself is not annotated,
    /// it's subterms may be, which would affect the upper 32 bits of
    /// `t.code()`.
    fn untyped_code(&self) -> Code;

    /// Substitute this term's variables recursively given a context
    fn subst_rec_id(&self, ctx: &mut (impl SubstCtx + ?Sized)) -> Result<Option<TermId>, Error> {
        Ok(self
            .subst_rec(ctx)?
            .map(|term| Self::ValueSubstituted::from(term).into_id_with(ctx.cons_ctx())))
    }

    /// Substitute this term's variables given a context
    fn subst_id(&self, ctx: &mut (impl SubstCtx + ?Sized)) -> Result<Option<TermId>, Error> {
        self.clone_into_term_direct().subst_id(ctx)
    }

    /// Shift this term's variables with index `>= base` up by `n` in a given context
    fn shift_id(
        &self,
        n: i32,
        base: u32,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        Ok(self
            .shift(n, base, ctx)?
            .map(|term| Self::ValueSubstituted::from(term).into_shallow_cons(ctx)))
    }

    /// Shift this term's variables with index `>= base` up by `n` in a given context
    fn shifted_id(
        &self,
        n: i32,
        base: u32,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<TermId, Error> {
        Ok(self
            .shift_id(n, base, ctx)?
            .unwrap_or_else(|| self.clone_into_id_with(ctx)))
    }

    /// Compare this term to another within a given context
    fn eq_term_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool>;

    /// Compare this term to a term ID, within a given context
    #[inline]
    fn eq_id_in(&self, other: &TermId, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        self.eq_term_in(&**other, ctx)
    }

    /// Cons this term within a given context. Return `None` if already consed.
    fn cons_id(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Option<TermId> {
        let code = self.code();
        if let Some(candidate) = ctx.uncons(code) {
            if self.eq_id_in(&candidate, &mut Structural).unwrap_or(false) {
                // Flag exchange
                candidate.set_flags(self.load_flags());
                self.set_flags(candidate.load_flags());
                return Some(candidate);
            }
            if code == candidate.code() {
                let collisions = TOTAL_HASH_COLLISIONS.fetch_add(1, Relaxed);
                if collisions == 0 || collisions.is_power_of_two() {
                    warn!(
                        "Hash collision detected for code {:?}. {} hash collisions have been detected so far.", 
                        self.code(), 
                        collisions
                    );
                }
            }
        }
        self.cons(ctx).map(|consed| {
            Self::ValueConsed::from(consed)
                .into_id_direct()
                .into_shallow_cons(ctx)
        })
    }

    /// Convert this term to a `TermId` within a given context
    fn into_id_with(self, ctx: &mut (impl ConsCtx + ?Sized)) -> TermId {
        if let Some(id) = self.cons_id(ctx) {
            id
        } else {
            let id = self.into_id_direct();
            if let Some(consed) = id.cons_id(ctx) {
                //TODO: think about this...
                consed
            } else {
                id
            }
        }
    }

    /// Get the type of this term, if any
    #[inline]
    fn ty(&self) -> Option<Cow<Term>> {
        if let Some(annot) = self.annot() {
            Some(annot.get_ty())
        } else {
            None
        }
    }

    /// Get the type of this term, if any
    #[inline]
    fn ty_id(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Option<Cow<TermId>> {
        if let Some(annot) = self.annot() {
            Some(annot.get_ty_id(ctx))
        } else {
            None
        }
    }

    /// Get the *transported* type of this term, if any
    #[inline]
    fn diff_ty(&self) -> Option<&TermId> {
        if let Some(annot) = self.annot() {
            annot.get_diff_ty()
        } else {
            None
        }
    }

    /// Get the base type of this term, if any
    #[inline]
    fn base(&self) -> Option<Cow<Term>> {
        if let Some(annot) = self.annot() {
            Some(annot.get_base())
        } else {
            None
        }
    }

    /// Get the type of this term, if any
    #[inline]
    fn base_id(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Option<Cow<TermId>> {
        if let Some(annot) = self.annot() {
            Some(annot.get_base_id(ctx))
        } else {
            None
        }
    }

    /// Apply this value, as a function, to a given vector of arguments in a given context
    /// Returns `None` if there is no change. Pops off consumed arguments.
    fn apply(
        &self,
        args: &mut SmallVec<[TermId; 2]>,
        ctx: &mut (impl EvalCtx + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        if self.is_local_function().unwrap_or(true) || args.is_empty() {
            self.subst_id(ctx)
        } else {
            Err(Error::ExpectedFunction)
        }
    }

    /// Apply this value, as a dependent function type, to a given vector of arguments in a given context
    /// Returns `None` if there is no change. Pops off consumed arguments.
    fn apply_ty(
        &self,
        args: &mut SmallVec<[TermId; 2]>,
        ctx: &mut (impl EvalCtx + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        if self.is_local_pi().unwrap_or(true) || args.is_empty() {
            self.subst_id(ctx)
        } else {
            Err(Error::ExpectedFunction)
        }
    }

    /// Convert this term to a `TermId`, without any consing
    #[inline]
    fn into_id_direct(self) -> TermId {
        TermId::from_term_direct(self.into_term_direct())
    }

    /// Clone this term to a `TermId`, without any consing
    #[inline]
    fn clone_into_id_direct(&self) -> TermId {
        self.clone().into_id_direct()
    }

    /// Clone this term to a `TermId` within a given context
    #[inline]
    fn clone_into_id_with(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> TermId {
        self.clone().into_id_with(ctx)
    }

    /// Clone this term to a `Term` without any consing
    #[inline]
    fn clone_into_term_direct(&self) -> Term {
        self.clone().into_term_direct()
    }

    /// Shallow cons a term directly into a context
    #[inline]
    fn into_shallow_cons(self, ctx: &mut (impl ConsCtx + ?Sized)) -> TermId {
        if let Some(consed) = ctx.uncons(self.code()) {
            if self.eq_term_in(&consed, &mut Structural).unwrap_or(false) {
                return consed;
            }
            //TODO: log hash collision?
        }
        self.into_id_direct().into_shallow_cons(ctx)
    }

    /// Shallow cons a term directly into a context, cloning if necessary
    #[inline]
    fn clone_into_shallow_cons(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> TermId {
        if let Some(consed) = ctx.uncons(self.code()) {
            if self.eq_term_in(&consed, &mut Structural).unwrap_or(false) {
                return consed;
            }
        }
        self.clone_into_id_direct().into_shallow_cons(ctx)
    }

    /// Get the form of this term
    fn form(&self) -> Form;

    /// Get whether this term is in head normal form
    #[inline]
    fn is_hnf(&self) -> bool {
        self.form().is_hnf()
    }

    /// Get whether this term is in beta normal form
    #[inline]
    fn is_bnf(&self) -> bool {
        self.form().is_bnf()
    }

    /// Get whether this term is in eta normal form
    #[inline]
    fn is_enf(&self) -> bool {
        self.form().is_enf()
    }

    /// Convert this term to a normal form
    #[inline]
    fn normalize(
        &self,
        form: Form,
        max_steps: u64,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        self.reduce(NormalCfg::to_form(form, max_steps), ctx)
    }

    /// Convert this term a normal form
    #[inline]
    fn normalized(
        &self,
        form: Form,
        max_steps: u64,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<TermId, Error> {
        self.reduced(NormalCfg::to_form(form, max_steps), ctx)
    }

    /// Convert this term to a normal form, or reduce it up to `n` steps
    #[inline]
    fn reduce(
        &self,
        cfg: impl ReductionConfig,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        let mut ctx = Reduce {
            eval_ctx: SubstVec::new(ctx),
            cfg,
        };
        let result = self.subst_id(&mut ctx);
        debug_assert!(ctx.eval_ctx.is_var_null());
        result
    }

    /// Convert this term a normal form, or reduce it up to `n` steps
    #[inline]
    fn reduced(
        &self,
        cfg: impl ReductionConfig,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<TermId, Error> {
        Ok(self
            .reduce(cfg, &mut *ctx)?
            .unwrap_or_else(|| self.clone_into_id_with(ctx.cons_ctx())))
    }

    /// Convert this term to a normal form, or reduce it up to `n` steps
    #[inline]
    fn reduce_until(
        &self,
        reduce: impl ReductionConfig,
        until: impl ctx::eval::TerminationCondition,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<TermId>, Error> {
        let cfg = ctx::eval::ReduceUntil { reduce, until };
        self.reduce(cfg, ctx)
    }

    /// Convert this term a normal form, or reduce it up to `n` steps
    #[inline]
    fn reduced_until(
        &self,
        reduce: impl ReductionConfig,
        until: impl ctx::eval::TerminationCondition,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<TermId, Error> {
        let cfg = ctx::eval::ReduceUntil { reduce, until };
        self.reduced(cfg, ctx)
    }
}

/// A term in `isotope`'s term language
#[derive(Clone, Eq)]
pub struct TermId(Arc<Term>);

impl TermId {
    /// Create a new `TermId` directly from a term, without any consing
    #[inline]
    pub fn from_term_direct(term: Term) -> TermId {
        TermId(Arc::new(term))
    }
}

/// An enumeration of terms in `isotope`'s term language
#[derive(Clone, Eq, PartialEq)]
pub enum Term {
    // Basic dependent type theory
    /// A function application
    App(App),
    /// A lambda function
    Lambda(Lambda),
    /// A dependent function type
    Pi(Pi),
    /// A variable
    Var(Var),
    /// A typing universe
    Universe(UniverseTerm),

    // Identity types:
    /// The reflexivity axiom
    Refl(Refl),
    /// Identity types
    Id(Id),

    // Basic extensions:
    //TODO: product
    //TODO: sum
    //TODO: sigma

    // Inductive types:
    //TODO: data-declaration
    //TODO: recursor/inductor/gamma

    // Generalized recursion:
    //TODO: phi
    //TODO: nontermination monad. Generalize?
    //TODO: nonterminating return. Generalize?

    // Representation:
    //TODO: uX, iX
    //TODO: struct
    //TODO: union

    // Program
    //TODO: (mutually recursive) function
    //TODO: (mutually recursive) block
    //TODO: (*non* recursive, for now) closure
    //TODO: call
    //TODO: switch
    //TODO: box
    //TODO: ref
    //TODO: deref

    // Primitives + denotation flag
    //TODO: unit
    /// An enumeration
    Enum(Enum),
    /// A variant of an enumeration
    Variant(Variant),
    /// A boolean term
    Boolean(Boolean),
    /// The type of booleans
    Bool(Bool),
    //TODO: nat
    //TODO: int

    // Builtin operations + denotation flag
    /// A case statement
    Case(Case),
    //TODO: logical
    //TODO: arithmetic
    //TODO: intrinsic

    // Dynamic extensions:
    /// A dynamic term
    Dynamic(DynamicTerm),
}

/// Return the same expression for every variant of `Term`
#[macro_export]
macro_rules! for_term {
    ($t:expr; $i:ident => $e:expr $(,$p:pat => $r:expr)*) => {
        {
            #[allow(unreachable_patterns)]
            match $t {
                $($p => $r,)*
                // Basic dependent type theory
                $crate::term::Term::App($i) => $e,
                $crate::term::Term::Lambda($i) => $e,
                $crate::term::Term::Pi($i) => $e,
                $crate::term::Term::Var($i) => $e,
                $crate::term::Term::Universe($i) => $e,

                // Identity types
                $crate::term::Term::Refl($i) => $e,
                $crate::term::Term::Id($i) => $e,

                // Primitives
                $crate::term::Term::Enum($i) => $e,
                $crate::term::Term::Variant($i) => $e,
                $crate::term::Term::Boolean($i) => $e,
                $crate::term::Term::Bool($i) => $e,

                // Primitive operations
                $crate::term::Term::Case($i) => $e,

                // Dynamic extensions
                $crate::term::Term::Dynamic($i) => $e,
            }
        }
    };
}

#[cfg(test)]
pub mod value_test_utils {
    use super::*;

    pub fn test_value_invariants<V>(value: &V, ctx: &mut (impl ConsCtx + ?Sized))
    where
        V: Value,
    {
        let is_pointer_cons = ctx.is_pointer_cons();
        let id = value.clone().into_id_with(ctx);
        assert_eq!(id.annot(), value.annot());
        assert_eq!(id, id.clone_into_id_direct());
        assert_eq!(id, id.clone().into_id_direct());
        let term = value.clone().into_term_direct();
        assert_eq!(term.annot(), value.annot());
        assert_eq!(term, value.clone_into_term_direct());
        assert_eq!(id, term.clone_into_id_direct());
        assert_eq!(id, term.clone().into_id_direct());
        let direct_id = value.clone().into_id_direct();
        assert_eq!(direct_id.annot(), value.annot());
        assert_eq!(direct_id, value.clone_into_id_direct());
        assert_eq!(direct_id, id);
        assert_eq!(*direct_id.0, term);
        let consed = value.cons_id(ctx);
        if is_pointer_cons {
            assert_eq!(id, value.clone_into_id_with(ctx).as_ptr());
            assert_eq!(id, id.clone_into_id_with(ctx).as_ptr());
            assert_eq!(id, id.clone().into_id_with(ctx).as_ptr());

            assert_eq!(id, term.clone().into_id_with(ctx).as_ptr());
            assert_eq!(id, term.clone_into_id_with(ctx).as_ptr());

            if let Some(consed) = consed {
                assert_eq!(id.as_ptr(), consed.as_ptr());
            }
        }
    }
}